<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\Model;

class AdminUser extends Model
{
    // 设置json类型字段
    protected $json = ['field'];

    protected $jsonAssoc = true;

    // 关联模型
    public function group()
    {
        return $this->hasOne(AdminGroup::class, 'id', 'group_id')->bind([
            'group_title' => 'title', 
            'group_role'  => 'role'
        ]);
    }

    // 修改器
    public function setPasswordAttr($value, $array)
    {
    	if (! empty($value)) {
    		$password = password_hash($value, PASSWORD_BCRYPT, ['cost' => 12]);	
	        $this->set('password', $password);
    	}
    }

    // 搜索器
    public function searchKeywordAttr($query, $value, $array)
    {
    	if (! empty($value)) {
	        $query->where("nickname|email|account",'like', '%' . $value . '%');
	    }
    }

    public function searchDateAttr($query, $value, $array)
    {
    	if (! empty($value)) { 
    		$query->whereBetweenTime('create_time', $value[0], $value[1]);
	    }
    }

    public function getPasswordAttr($value, $array)
    {
        return '';
    }

    // 获取器
    public function getFieldAttr($value, $array)
    {
        $event = event("UserAdminField");
        $field = [];
        foreach ($event as $key => $val) {
            foreach ($val as $k => $v) {
                array_push($field, $v);
            }
        }
        if (! empty($field)) {
            foreach ($field as $k => $v) {
                $field[$k]['value'] = isset($value[$v['field']]) ? $value[$v['field']] : $v['value'];
            }
        }
        return $field;
    }
    
    // 修改器
    public function setFieldAttr($value, $array)
    {
        $field = [];
        foreach ($value as $key => $val) {
            $field[$val['field']] = $val['value'];
        }
        return $field;
    }
}